//https://blog.csdn.net/zl1zl2zl3/article/details/81357146
import React, {
	PureComponent,
	Fragment
} from 'react';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import {
	Row,
	Col,
	Card,
	Form,
	Input,
	Select,
	Icon,
	Button,
	Modal,
	message,
	Divider,
	Table,
	DatePicker,
	Steps,
  Tabs
} from 'antd';
//import StandardTable from '@/components/StandardTable';
import SelectPoliceRankTree from '@/components/SelectPoliceRankTree';
import SelectDutyLevelTree from '@/components/SelectDutyLevelTree';
import SelectWorkTree from '@/components/SelectWorkTree';
import SelectChangeTypeTree from '@/components/SelectChangeTypeTree';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';

import ProUserViewForm from './ProUserViewForm';//查看存档
import CommandModal from './CommandModal'; //命令弹窗
import MemberApproveModal from './MemberApproveModal';//生成审批表
import ReturnModal from './ReturnModal';//退回人员
import styles from './ProUserList.less';
import {getValue} from '@/utils/globalcommon';
import {initTotalList} from '@/utils/globalcommon';
const FormItem = Form.Item;
const { Option } = Select;
const { confirm } = Modal;
const { Step } = Steps;
const { TabPane } = Tabs;

//用户列表

class StandardTable extends PureComponent {

  constructor(props) {
    super(props);
    const { columns } = props;
    const needTotalList = initTotalList(columns);

    this.state = {
      selectedRowKeys: [],
      needTotalList,
    };
  }

  static getDerivedStateFromProps(nextProps) {
    // clean state
    if (nextProps.selectedRows.length === 0) {
      const needTotalList = initTotalList(nextProps.columns);
      return {
        selectedRowKeys: [],
        needTotalList,
      };
    }
    return null;
  }

  handleRowSelectChange = (selectedRowKeys, selectedRows) => {
    let { needTotalList } = this.state;
    needTotalList = needTotalList.map(item => ({
      ...item,
      total: selectedRows.reduce((sum, val) => sum + parseFloat(val[item.dataIndex], 10), 0),
    }));
    const { onSelectRow } = this.props;
    if (onSelectRow) {
      onSelectRow(selectedRows);
    }

    this.setState({ selectedRowKeys, needTotalList });
  };

  handleTableChange = (pagination, filters, sorter) => {
    const { onChange } = this.props;
    if (onChange) {
      onChange(pagination, filters, sorter);
    }
  };

  cleanSelectedKeys = () => {
    this.handleRowSelectChange([], []);
  };

  render() {
    const { selectedRowKeys, needTotalList } = this.state;
    const { data = {}, rowKey, ...rest } = this.props;
    const { list = [], pagination } = data;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      current:pagination? pagination.currentPage : 1,
      ...pagination,
    };

    const rowSelection = {
      selectedRowKeys,
      onChange: this.handleRowSelectChange,
      getCheckboxProps: record => ({
        disabled: record.disabled,
      }),
    };

    return (
      <div className={styles.standardTable}>
        <Table
          rowKey={rowKey || 'key'}
          rowSelection={rowSelection}
          dataSource={data}
          pagination={paginationProps}
          onChange={this.handleTableChange}
          {...rest}
          size="middle"
          scroll={{x: 'max-content'}}
        />
      </div>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({
	policeapprove,
	loading
}) => ({
	policeapprove,
	loading: loading.models.policeapprove,
}))

@Form.create()
class ProApproveList extends PureComponent {
	state = {
		viewModalVisible: false,
		expandForm: false,
		selectedRows: [],
		formValues: {},
		requestModelName:"policeapprove",
		currentPage: 1,
		pageSize: 10,

		current: 0,
		modalVisibleByMemberApprove: false,
    resetFlag: false,
    modalVisibleByCommand: false
	};

  //查看命令文件
  handleModalVisibleByCommand = flag => {

    const { selectedRows } = this.state;
    if(selectedRows.length > 0) {
  		this.setState({
  			modalVisibleByCommand: !!flag,
  		});
    	if(flag) {
    		message.success('生成成功');
    	}
    }else {
    	Modal.warning({
    	    title: '请选择人员',
    	    okText: '确认',
    	    centered: true,
    	});
    }
  };


  //退回原因弹窗
  handleModalVisibleByReturn = flag => {
  	const { selectedRows } = this.state;
  	if(selectedRows.length > 0) {
  		this.setState({
  			modalVisibleByReturn: !!flag,
  		});
  	}else {
  		Modal.warning({
  		    title: '请选择人员',
  		    okText: '确认',
  		    centered: true,
  		});
  	}
  };

  handleAddByReturn = (fieldsValue) => {
  	const { dispatch } = this.props;
    dispatch({
    	type: 'policeapprove/query_page_for_policeapprove',
      payload: {
          returnid: 1
      }
    });
  	message.success('操作成功');
    this.setState({
    	selectedRows: []
    });
  	this.handleModalVisibleByReturn();
  };


	//生成命令
	// handleModalVisibleByCommand = flag => {
	// 	const { selectedRows } = this.state;
	// 	const _this = this;
	// 	if(selectedRows.length > 0) {
	// 		if(selectedRows.length > 2) {

	// 		}else {
	// 			Modal.success({
	// 			    title: '生成成功',
	// 			    content: '',
	// 			    okText: '确认',
	// 			    centered: true,
	// 			    onOk() {

	// 			    },
	// 			    onCancel() {},
	// 			});
	// 			this.setState({
	// 				current:1,
	// 			});
	// 		}
	// 	}else {
	// 		Modal.warning({
	// 		    title: '请选择人员',
	// 		    okText: '确认',
	// 		    centered: true,
	// 		});
	// 	}
	// };

	//审批表
	handleModalVisibleByMemberApprove = flag => {
		const { selectedRows } = this.state;
		if(selectedRows.length > 0) {
			this.setState({
				modalVisibleByMemberApprove: !!flag,
			});
			if(flag) {
				message.success('生成成功');
				this.setState({
					current:2,
				});
			}
		}else {
			Modal.warning({
			    title: '请选择一条记录',
			    okText: '确认',
			    centered: true,
			});
		}

	};

	//结果回填
	handleModalVisibleByResultReturn = flag => {
		const { selectedRows } = this.state;
		const _this = this;
    const { dispatch } = this.props;
		if(selectedRows.length > 0) {
			if(selectedRows.length > 2) {

			}else {
				Modal.success({
				    title: '回填成功',
				    content: '可在人员基本信息管理中查看',
				    okText: '确认',
				    centered: true,
				    onOk() {

				    },
				    onCancel() {},
				});
				this.setState({
					current:2,
				});
			}
      dispatch({
      	type: 'policeapprove/query_page_for_policeapprove',
        payload: {
           returnid: 2
        }
      });
		}else {
			Modal.warning({
			    title: '请选择人员',
			    okText: '确认',
			    centered: true,
			});
		}
	};

	handleAddByMemberApprove = () => {
		const { dispatch } = this.props;

		this.handleModalVisibleByMemberApprove();

	};

	columns = [
        {
	        title: '单位',
	        dataIndex: 'unit',
	        key: 'unit',
        }, 	{
	        title: '姓名',
	        dataIndex: 'name',
	        key: 'name',
        },  {
	        title: '性别',
	        dataIndex: 'sex',
	        key: 'sex',
        },  {
	        title: '出生日期',
	        dataIndex: 'date_of_birth',
	        key: 'date_of_birth',
        },{
	        title: '职务',
	        dataIndex: 'post',
	        key: 'post',
        }, {
	        title: '职务层次',
	        dataIndex: 'duty_level',
	        key: 'duty_level',
        }, {
	        title: '变动类型',
	        dataIndex: 'change_type',
	        key: 'change_type',
        },{
	        title: '现任警衔',
	        dataIndex: 'incumbent_police_rank',
	        key: 'incumbent_police_rank',
        },{
	        title: '现任警衔起算日期',
	        dataIndex: 'start_time',
	        key: 'start_time',
        },{
	        title: '拟授警衔',
	        dataIndex: 'police_rank',
	        key: 'police_rank',
        },{
	        title: '新警衔起算日期',
	        dataIndex: 'new_start_time',
	        key: 'new_start_time',
        },{
	        title: '任职时间',
	        dataIndex: 'appointment_time',
	        key: 'appointment_time',
        }, {
	        title: '参加工作时间',
	        dataIndex: 'working_hours',
	        key: 'working_hours',
        },  {
	        title: '学制年限',
	        dataIndex: 'educational_system',
	        key: 'educational_system',
        }, {
			title: '操作',
			fixed:'right',
			align: 'center',
    		width: 160,
			render: (text, record) => {
	        	return (
		        	<Fragment>

                <a onClick={() => this.handleViewModalVisible(true, record)}>查看</a>

				    </Fragment>
	        	);

			}
		},
	];

	componentDidMount() {
		const { dispatch } = this.props;
		dispatch({
			type: 'policeapprove/query_page_for_policeapprove',
		});
	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
		const { dispatch } = this.props;
		const { formValues } = this.state;

		this.setState({
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			selectedRows: [],
		})

		const filters = Object.keys(filtersArg).reduce((obj, key) => {
			const newObj = { ...obj
			};
			newObj[key] = getValue(filtersArg[key]);
			return newObj;
		}, {});

		const params = {
			currentPage: pagination.current,
			pageSize: pagination.pageSize,
			...formValues,
			...filters,
		};
		if(sorter.field) {
			params.sorter = `${sorter.field}_${sorter.order}`;
		}

		dispatch({
			type: 'policeapprove/query_page_for_policeapprove',
			payload: params,
		});
	};

	previewItem = id => {
		router.push(`/profile/basic/${id}`);
	};

	handleFormReset = () => {
		const { form,dispatch } = this.props;
		form.resetFields();
		this.setState({
				formValues: {},
				currentPage:1,
				selectedRows: [],
        resetFlag: true,
		});
		dispatch({
			type: 'policeapprove/query_page_for_policeapprove',
		});
	};

	toggleForm = () => {
		const { expandForm } = this.state;
		this.setState({
			expandForm: !expandForm,
		});
	};


	handleSelectRows = rows => {
		this.setState({
			selectedRows: rows,
		});
	};

	handleSearch = e => {
		e.preventDefault();

		const {
			dispatch,
			form
		} = this.props;

		form.validateFields((err, fieldsValue) => {
			if(err) return;

      const { getPoliceRankTreeBySelectTree,getDutyLevelTreeBySelectTree,getWorkTreeBySelectTree,getChangeTypeTreeBySelectTree } = this.state;
      if (getPoliceRankTreeBySelectTree) {
        fieldsValue.police_rank = getPoliceRankTreeBySelectTree.triggerNode.props.dataRef.title;
      }

      if (getDutyLevelTreeBySelectTree) {
        fieldsValue.duty_level = getDutyLevelTreeBySelectTree.triggerNode.props.dataRef.title;
      }

      if (getWorkTreeBySelectTree) {
        fieldsValue.company = getWorkTreeBySelectTree.triggerNode.props.dataRef.title;
      }

      if (getChangeTypeTreeBySelectTree) {
        fieldsValue.change_type = getChangeTypeTreeBySelectTree.triggerNode.props.dataRef.title;
      }

			const values = {
				...fieldsValue,
				updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
			};

			this.setState({
				currentPage:1,
				selectedRows: [],
				formValues: values,
        resetFlag: false,
			});

			dispatch({
				type: 'policeapprove/query_page_for_policeapprove',
				payload: values,
			});
		});
	};


	handleViewModalVisible = (flag, record) => {
		this.setState({
			viewModalVisible: !!flag,
			viewFormValues: record || {},
		});
	};


	//拟授警衔
	selectedPoliceRankTreeValue = (deptRecord) => {
		  this.setState({
  			getPoliceRankTreeBySelectTree: deptRecord,
  		})
	}

	//职务层次
	selectedDutyLevelTreeValue = (deptRecord) => {
		  this.setState({
  			getDutyLevelTreeBySelectTree: deptRecord,
  		})
	}

	//单位
	selectedWorkTreeValue = (deptRecord) => {
		  this.setState({
  			getWorkTreeBySelectTree: deptRecord,
  		})
	}

	//变动类型
	selectedChangeTypeTreeValue = (deptRecord) => {
		  this.setState({
  			getChangeTypeTreeBySelectTree: deptRecord,
  		})
	}

	renderSimpleForm() {
		const {
			form: {
				getFieldDecorator
			},
			policeapprove: {
				selectPoliceRankTree
			},
		} = this.props;
		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
      resetFlag: this.state.resetFlag
		}
		return(
		<Form onSubmit={this.handleSearch} layout="inline">
	      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
					<Col md={8} sm={24}>
			        <FormItem label="姓名">
			        	{getFieldDecorator('name')(<Input placeholder="请输入" />)}
							</FormItem>
			    </Col>
		      <Col md={8} sm={24}>
			        <FormItem label="拟授警衔">
			        	{getFieldDecorator('police_rank')(<SelectPoliceRankTree  {...parentPoliceRankTreeMethod}/>)}
							</FormItem>
		    	</Col>
			    <Col md={8} sm={24}>
			        <span className={styles.submitButtons}>
			        <Button type="primary" htmlType="submit">
			        	查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        	重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        	展开 <Icon type="down" />
			        </a>
			        </span>
		        </Col>
	        </Row>
        </Form>
		);
	}

	renderAdvancedForm() {
		const {
			form: {
				getFieldDecorator
			},
			policeapprove: {
				selectPoliceRankTree,
				selectDutyLevelTree,
				selectWorkTree,
				selectChangeTypeTree,
			},
		} = this.props;
		const parentPoliceRankTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedPoliceRankTreeValue: this.selectedPoliceRankTreeValue,
			selectPoliceRankTree,
      resetFlag: this.state.resetFlag
		}
		const parentDutyLevelTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedDutyLevelTreeValue: this.selectedDutyLevelTreeValue,
			selectDutyLevelTree,
      resetFlag: this.state.resetFlag
		}
		const parentWorkTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedWorkTreeValue: this.selectedWorkTreeValue,
			selectWorkTree,
      resetFlag: this.state.resetFlag
		}
		const parentChangeTypeTreeMethod = {
			dispatch: this.props.dispatch,
			requestModelName: this.state.requestModelName,
			selectedChangeTypeTreeValue: this.selectedChangeTypeTreeValue,
			selectChangeTypeTree,
      resetFlag: this.state.resetFlag
		}
		return(
			<Form onSubmit={this.handleSearch} layout="inline">
		      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
							<Col md={8} sm={24}>
						        <FormItem label="姓名">
						        	{getFieldDecorator('name')(<Input placeholder="请输入" />)}
								</FormItem>
						    </Col>
					      <Col md={8} sm={24}>
						        <FormItem label="拟授警衔">
						        	{getFieldDecorator('police_rank')(<SelectPoliceRankTree  {...parentPoliceRankTreeMethod}/>)}
										</FormItem>
					    	</Col>
					      <Col md={8} sm={24}>
						        <FormItem label="职务层次">
						        	{getFieldDecorator('duty_level')(<SelectDutyLevelTree  {...parentDutyLevelTreeMethod}/>)}
										</FormItem>
					    	</Col>
		    	</Row>
		      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
				      <Col md={8} sm={24}>
						        <FormItem label="单位">
						        	{getFieldDecorator('company')(<SelectWorkTree  {...parentWorkTreeMethod}/>)}
										</FormItem>
					    	</Col>
				      <Col md={8} sm={24}>
						        <FormItem label="变动类型">
						        	{getFieldDecorator('change_type')(<SelectChangeTypeTree  {...parentChangeTypeTreeMethod}/>)}
										</FormItem>
					    	</Col>
					    <Col md={8} sm={24}>
				        <FormItem label="人员记录">
				            {getFieldDecorator('ryjl')(
				                <Select placeholder="请选择" style={{ width: '100%' }}>
				                    <Option value="1">全部</Option>
				                    <Option value="0">重复</Option>
				                </Select>
				            )}
				        </FormItem>
			        </Col>
		    	</Row>
			    <div style={{ overflow: 'hidden' }}>
					<div style={{ marginBottom: 24 }}>
					<Button type="primary" htmlType="submit">
			        查询
			        </Button>
			        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
			        重置
			        </Button>
			        <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
			        收起 <Icon type="up" />
			        </a>
		        	</div>
		        </div>
        </Form>
		);
	}

	renderForm() {
		const {
			expandForm
		} = this.state;

		return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
	}

	render() {
		const steps = [
		  {
		    title: '生成命令',
		  },
		  {
		    title: '生成审批表',
		  },
		  {
		    title: '结果回填',
		  },
		];
		const {
			policeapprove: {
				data,
			},
			loading,
		} = this.props;
		const {
			selectedRows,
			viewModalVisible,
			current,
			modalVisibleByMemberApprove,
      modalVisibleByReturn,
      modalVisibleByCommand
		} = this.state;

		const viewMethods = {
			handleViewModalVisible: this.handleViewModalVisible
		};

    //退回人员
    const parentMethodsByReturn = {
    	handleModalVisibleByReturn: this.handleModalVisibleByReturn,
    	handleAddByReturn: this.handleAddByReturn,
    	modalVisibleByReturn
    };

		//生成审批表
		const parentMethodsByMemberApprove = {
			handleModalVisibleByMemberApprove: this.handleModalVisibleByMemberApprove,
			handleAddByMemberApprove: this.handleAddByMemberApprove,
			modalVisibleByMemberApprove
		};

    //查看命令文件
    const parentMethodsByCommand = {
    	handleModalVisibleByCommand: this.handleModalVisibleByCommand,
    	modalVisibleByCommand
    };

		return(
			<PageHeaderWrapper title="警衔审批列表">
            <Card bordered={false}>
            <div className={styles.proUsertableList}>
            <div className={styles.proUsertableListForm}>{this.renderForm()}</div>
            <div className={styles.proUsertableListOperator}>
        	{/*<Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
    		新增
    		</Button>*/}
        	<Steps current={current} size="small" style={{width: '80%',marginBottom: '30px',marginTop: '10px'}}>
	          {steps.map(item => (
	            <Step key={item.title} title={item.title} />
	          ))}
	        </Steps>
        <Button type="primary" onClick={() => this.handleModalVisibleByReturn(true)} style={{marginRight: '25px'}}>
        退回
        </Button>
    		<Button type="primary" onClick={() => this.handleModalVisibleByCommand(true)} style={{marginRight: '25px'}}>
    		生成命令
    		</Button>
    		<Button type="primary" onClick={() => this.handleModalVisibleByMemberApprove(true)} style={{marginRight: '25px'}}>
    		生成审批表
    		</Button>
    		<Button type="primary" onClick={() => this.handleModalVisibleByResultReturn(true)} style={{marginRight: '25px'}}>
    		数据回填
    		</Button>
    	</div>
      {data.list.length > 0?(
        <Tabs type="card">
          {data.list.map(item => {
            return (
              <TabPane tab={item.title} key={item.key} closable={item.closable}>
              <StandardTable
                rowKey={"user_id"}
                selectedRows={selectedRows}
                loading={loading}
                data={item.children}
                columns={this.columns}
                onSelectRow={this.handleSelectRows}
                onChange={this.handleStandardTableChange}
                />
              </TabPane>
            )
          })}
        </Tabs>
      ):(
          <StandardTable
          rowKey={"user_id"}
          selectedRows={selectedRows}
          loading={loading}
          data={[]}
          columns={this.columns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
          />
      )}
        </div>
        </Card>
    <ProUserViewForm
    {...viewMethods}
    viewModalVisible={viewModalVisible}
    />
		<MemberApproveModal {...parentMethodsByMemberApprove}/>
    <ReturnModal {...parentMethodsByReturn}/>
    <CommandModal {...parentMethodsByCommand}/>
    </PageHeaderWrapper>
		);
	}
}

export default ProApproveList;
